//
//  GLViewController.mm
//  Texture
//
//  Created by wq on 11-8-16.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "GLViewController.h"
#import "GLView.h"
#import "glues.h"

@interface GLViewController ()

@property(nonatomic, retain) EAGLContext *context;
@property(nonatomic, assign) CADisplayLink *dispLink;

-(void)drawFrame;
-(void)createTexture;

@end


@implementation GLViewController

@synthesize animating;
@dynamic frameInterval;

@synthesize context;
@synthesize dispLink;

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
	[super viewDidUnload];
}

- (void)dealloc {
	[context release];
	[super dealloc];
}

-(void)createTexture {
	glEnable(GL_TEXTURE_2D);
	//glEnable(GL_BLEND);
	//glBlendFunc(GL_ONE, GL_SRC_COLOR);
	
	glGenTextures(4, textures);
	
	// 加载方法一：加载 UIImage 支持的图片格式，再利用 CoreGraphics 转换为 OES 支持的 RGBA 位图格式
	// 图片大小要求为 2 的 n 次幂
	NSString *path = [[NSBundle mainBundle] pathForResource:@"texture0" ofType:@"png" inDirectory:@"res"];
	CGImageRef imgRef = [UIImage imageWithContentsOfFile:path].CGImage;
	if (imgRef == nil)
		NSLog(@"Do real error checking here");

	GLuint width = CGImageGetWidth(imgRef);
	GLuint height = CGImageGetHeight(imgRef);
	void *imageData = malloc( height * width * 4 );
	CGContextRef cgContex = CGBitmapContextCreate( imageData, width, height, 8, 4 * width,
												 CGImageGetColorSpace(imgRef), kCGImageAlphaPremultipliedLast );
	
	// CoreGraphics 的坐标系与 OES 坐标系 y 轴是相反的，修改CoreGraphics坐标系与OES一致
	// 利用opengl 纹理坐标来实现上下翻转，减少调用，加快资源载入
	//CGContextTranslateCTM( cgContex, 0, height );
	//CGContextScaleCTM(cgContex, 1.0f, -1.0f);
	
	CGContextDrawImage( cgContex, CGRectMake( 0, 0, width, height ), imgRef );

	glBindTexture(GL_TEXTURE_2D, textures[0]);
	
	// iOS 纹理默认启用了 mipmap，改用指定的插值算法，每个纹理都要单独指定
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA,
				 GL_UNSIGNED_BYTE, imageData);

	CGContextRelease(cgContex);
	free(imageData);
	
	// 图片大小非 2 的 n 次幂
	path = [[NSBundle mainBundle] pathForResource:@"texture1" ofType:@"png" inDirectory:@"res"];
	imgRef = [UIImage imageWithContentsOfFile:path].CGImage;
	if (imgRef == nil)
		NSLog(@"Do real error checking here");
	
	width = CGImageGetWidth(imgRef);
	height = CGImageGetHeight(imgRef);
	imageData = malloc( 512 * 512 * 4 );
	cgContex = CGBitmapContextCreate( imageData, 512, 512, 8, 4 * 512,
												  CGImageGetColorSpace(imgRef), kCGImageAlphaPremultipliedLast );
	
	CGContextClearRect(cgContex, CGRectMake(0, 0, 512, 512));
	
	// 同样不调用 CGContextTranslateCTM 和 CGContextScaleCTM
	// opengl 纹理坐标只对 CoreGraphics 的坐标翻转，图片并不翻转
	//CGContextTranslateCTM( cgContex, 0, height );
	//CGContextScaleCTM(cgContex, 1.0f, -1.0f);
	
	_maxS = 320.0f / 512.0f;
	_minT = (512.0f - 480.0f) / 512.0f;
	
	CGContextDrawImage( cgContex, CGRectMake( 0, 0, width, height ), imgRef );
	
	glBindTexture(GL_TEXTURE_2D, textures[1]);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 512, 512, 0, GL_RGBA,
				 GL_UNSIGNED_BYTE, imageData);
	
	CGContextRelease(cgContex);
	free(imageData);
}

-(id)init {
	self = [super init];
	if (self) {
		EAGLContext *ctx = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];
		self.context = ctx;
		[ctx release];
		
		GLView *v = [[GLView alloc] initWithFrame:[UIScreen mainScreen].bounds];
		self.view = v;
		[v release];
		
		v.context = context;
		[v initViewport];
		
		animating = NO;
		frameInterval = 2;
		
		[self createTexture];
	}
	return self;
}

-(void)startAnimation {
	if (!animating) {
		CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(drawFrame)];
		self.dispLink = displayLink;
		[displayLink setFrameInterval:frameInterval];
		[displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
		animating = YES;
	}
}

-(void)stopAnimation {
	if (animating) {
		[dispLink invalidate];
		self.dispLink = nil;
		animating = NO;
	}
}

-(void)drawFrame {
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();
	
	gluLookAtf(0.0f, 0.0f, 415.6921938165306f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
	
	//glColor4f(1.0f, 0.0f, 1.0f, 1.0f);
	
	// 左上
	glPushMatrix();
	glTranslatef(-80.0f, 120.0f, 0.0f);
	
	static GLfloat rot = -6.6f;
	rot += 6.6f;
	//glRotatef(rot, -1.0f, 0.0f, 0.0f);
	
	// 调用 CGContextTranslateCTM 和 CGContextScaleCTM 时的纹理坐标
	/*static const GLfloat vertices[] = {
		-50.0f, -50.0f, 0.0f,		0.0f, 0.0f,
		 50.0f, -50.0f, 0.0f,		1.0f, 0.0f,
		-50.0f,  50.0f, 0.0f,		0.0f, 1.0f,
		 50.0f,  50.0f, 0.0f,		1.0f, 1.0f,
	};*/
	
	// 不调用的情况下
	static const GLfloat vertices[] = {
		-50.0f, -50.0f, 0.0f,		0.0f, 1.0f,
		50.0f, -50.0f, 0.0f,		1.0f, 1.0f,
		-50.0f,  50.0f, 0.0f,		0.0f, 0.0f,
		50.0f,  50.0f, 0.0f,		1.0f, 0.0f,
	};
	
	glVertexPointer(3, GL_FLOAT, 5 * sizeof(GLfloat), vertices);
	glEnableClientState(GL_VERTEX_ARRAY);
	
	glTexCoordPointer(2, GL_FLOAT, 5 * sizeof(GLfloat), vertices + 3);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
	
	glBindTexture(GL_TEXTURE_2D, textures[0]);
	glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
	glPopMatrix();
	
	// 右上
	glPushMatrix();
	glTranslatef(80.0f, 120.0f, 0.0f);
	
	//glRotatef(rot, 0.0f, 1.0f, 0.0f);
	static const GLbyte vertexIdx[] = {
		0, 1, 2, 3,
	};
	
	static const GLfloat texCoord1[] = {
		0.0f, 0.0f,		0.0f, 1.0f,		0.0f, 1.0f,
		1.0f, 0.0f,		1.0f, 1.0f,		_maxS, 1.0f,
		0.0f, 1.0f,		0.0f, 0.0f,		0.0f, _minT,
		1.0f, 1.0f,		1.0f, 0.0f,		_maxS, _minT,
	};
	
	glBindTexture(GL_TEXTURE_2D, textures[1]);
	
	//glTexCoordPointer(2, GL_FLOAT, 6 * sizeof(GLfloat), texCoord1);
	//glTexCoordPointer(2, GL_FLOAT, 6 * sizeof(GLfloat), texCoord1+2);
	glTexCoordPointer(2, GL_FLOAT, 6 * sizeof(GLfloat), texCoord1+4);
	
	glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_BYTE, vertexIdx);
	glPopMatrix();
	
	[(GLView *)self.view presentRenderbuffer];
}

@end
